<script>
// import LabelText from '../comm/LabelText'
import AddImg from '../comm/AddImg'
import fileSelect from '../comm/file-select'
import ajaxApi from '../ajax-api'
export default {
  render () {
    let initSrc = this.src
    return (
      <div class="set-item">
        <div class="tit">图片</div>
        <div class="it">
          <AddImg ref="vAddImg" onAdd={this.onAdd} onChange={this.onChange} initImages={initSrc ? [initSrc] : undefined} btnText="选择图片" hasBtnText="重新选择" isUploading={this.isUploading} onCancel={this.onAbort}/>
        </div>
      </div>
    )
  },
  props: {
    src: String
  },
  data () {
    return {
      isUploading: false
    }
  },
  methods: {
    onAdd () {
      this.upload().finally(() => {
        this.isUploading = false
      })
    },
    async upload () {
      const file = await fileSelect({
        accept: 'image/*',
        fileSizeLimit: 30,
        onError: (error) => {
          this.$toast.error(error.message)
        }
      })
      this.isUploading = true
      const { vAddImg } = this.$refs
      const { url } = await ajaxApi.fileUpload({
        file,
        onProgress: (p) => {
          vAddImg.progressText = ~~(p * 100 - 1) + '%'
        },
        cancelToken: cancel => {
          this.abortFileUpload = cancel
        }
      })
      vAddImg.progressText = ''
      vAddImg.addSingle(url)
    },
    onChange ({ 0: image }) {
      this.$emit('change', image || '')
      // dataApi.currActiveItem.image = image || ''
    },
    onAbort () {
      this.abortFileUpload()
    }
  }
}
</script>
